import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_topic_list_state.dart';

import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class TopicRecomendListNotifier extends AsyncNotifier<LifeTopicListState> {
  int pageSize = 10;
  int pageNum = 1;

  @override
  Future<LifeTopicListState> build() async {
    return _fetchData();
  }

  Future<void> refresh() async {
    try {
      pageNum = 1;
      final newState = await _fetchData();
      state = AsyncValue.data(newState);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  Future<LifeTopicListState> _fetchData() async {
    final ret = await ref
        .read(topicRecommendListUsecaseProvider)
        .execute(pageNum: pageNum, pageSize: pageSize);
    return LifeTopicListState(
      data: LifeTopicModule.listFromApi(ret.rows ?? []),
      totalSize: ret.total,
      page: pageNum,
      pageSize: pageSize,
      isLoadingMore: false,
      hasMore: ret.total > (ret.rows ?? []).length,
    );
  }

  Future<void> loadMore() async {
    final current = state.valueOrNull;
    if (current == null || current.isLoadingMore || !current.hasMore) return;

    state = AsyncValue.data(current.copyWith(isLoadingMore: true));

    final nextPage = current.page + 1;
    final ret = await ref
        .read(topicRecommendListUsecaseProvider)
        .execute(pageNum: nextPage, pageSize: pageSize);

    state = AsyncValue.data(
      LifeTopicListState(
        data: [
          ...current.data ?? [],
          ...LifeTopicModule.listFromApi(ret.rows ?? []),
        ],
        page: nextPage,
        totalSize: ret.total,
        pageSize: current.pageSize,
        isLoadingMore: false,
        hasMore:
            ret.total > (current.data ?? []).length + (ret.rows ?? []).length,
      ),
    );
  }

  /// 更新指定 topic 的关注状态
  void updateTopicFollowStatus(String topicId, bool isFollowed) {
    final current = state.valueOrNull;
    if (current == null || current.data == null) return;

    final updatedData = current.data!.map((topic) {
      if (topic.id == topicId) {
        // 创建新的 LifeTopicModule，更新关注状态
        return topic.copyWith(isFollow: isFollowed);
      }
      return topic;
    }).toList();

    state = AsyncValue.data(current.copyWith(data: updatedData));
  }
}
